﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;

namespace Atlepage.State
{
    [Serializable]
    internal class ManagerState
    {
        public object t;
        public string version;
        public ManagerState(object t, string version)
        {
            this.t = t;
            this.version = version;
        }
    }
    class Manager<T> where T : class
    {
        string version;
        string file;

        public Manager(string ext)
        {
            Assembly assembly = Assembly.GetEntryAssembly();
            version = assembly.FullName;
            file = assembly.CodeBase + ext;
            if (Environment.OSVersion.Platform == PlatformID.Unix)
                file = file.Substring(7);
            else
                file = file.Substring(8);
        }

        public T Load()
        {
            if (!File.Exists(file))
                return null;

            SoapFormatter formatter = new SoapFormatter();
            using (Stream stream = File.Open(file, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    ManagerState state = (ManagerState)formatter.Deserialize(stream);
                    if (state.version == version)
                        return (T)state.t;
                }
                catch { }
            }
            return null;
        }

        public void Save(T t)
        {
            SoapFormatter formatter = new SoapFormatter();
            using (Stream stream = File.Open(file, FileMode.Create, FileAccess.Write))
            {
                formatter.Serialize(stream, new ManagerState(t, version));
            }
        }
    }
}
